using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SimpleFramework
{
    public class Sound
    {
        public static readonly SimplePool<Sound> Pool = new SimplePool<Sound>();

        public string assetPath;
        public AudioClip clip;
        public bool loop = false;
        public float volume = 1.0f;
        public float volumeScale = 1.0f;
        public AudioSource player;

        public void Play()
        {
            if (this.clip != null)
            {
                Play(this.clip);
            }
            else
            {
                Res.Spawn(assetPath, OnPlaySound);
            }
        }

        private void OnPlaySound(IResObjectPool pool, object userData)
        {
            var clip = pool.Spawn<AudioClip>();
            Play(clip);
        }

        private void Play(AudioClip clip)
        {
            this.player.clip = clip;
            this.player.loop = this.loop;
            this.player.volume = this.volume * this.volumeScale;
            this.player.Play();
            if (!this.loop)
            {
                MacroUtils.DelayCall(clip.length * 1.5f, OnComplete);
            }
        }

        private void OnComplete()
        {
            if (this.player.clip)
            {
                Res.UnSpawn(this.player.clip);
                this.player.clip = null;
            }
            SoundManager.Instance.RemoveSound(this);
            Pool.UnSpawn(this);
            if (this.clip)
            {
                AudioClip.DestroyImmediate(this.clip);
                this.clip = null;
            }
        }

        public void Stop()
        {
            SoundManager.Instance.RemoveSound(this);
            Pool.UnSpawn(this);
        }

        public void Pause()
        {
            if (this.player != null)
            {
                this.player.Pause();
            }
        }

        public void Resume()
        {
            if (this.player != null)
            {
                this.player.UnPause();
            }
        }

        public void RefreshVolume()
        {
            if (this.player != null)
            {
                this.player.volume = this.volume * this.volumeScale;
            }
        }
    }
}